<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区 -->
      <el-alert title="添加商品信息" type="info" show-icon center :closable="false"></el-alert>
      <!-- 步骤条区域 -->
      <el-steps :space="200" :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 侧边导航 -->
      <el-form
        :model="addForm"
        :rules="rulesAdd"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="leaveTab"
          @tab-click="clickTab"
        >
          <!-- 商品基本信息 -->
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_name">
              <!-- options数据源  v-moder 选中的value -->
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="configCascader"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品参数 -->
          <el-tab-pane name="1" label="商品参数">
            <el-form-item :label="item.attr_name" v-for="item in manyData" :key="item.attr_id">
              <el-checkbox
                border
                :label="item1"
                v-for="(item1,index) in item.attr_vals"
                :key="index"
                :checked="true"
              ></el-checkbox>
            </el-form-item>
          </el-tab-pane>
          <!-- 商品属性 -->
          <el-tab-pane name="2" label="商品属性">
            <el-form-item v-for="item in onlyData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <!-- 图片上传 -->
          <el-tab-pane name="3" label="商品图片">
            <el-upload
              action="http://127.0.0.1:8888/api/private/v1/upload"
              list-type="picture-card"
              :auto-upload="true"
              :headers="headers"
              :file-list="thislist"
              :on-success="success"
            >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{file}">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
            <!-- 弹窗放大图片 -->
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt />
            </el-dialog>
          </el-tab-pane>
          <!-- 商品内容富文本 -->
          <el-tab-pane name="4" label="商品内容">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="addBtn" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import _ from "lodash";
export default {
  data() {
    return {
      //控制进度
      activeIndex: "0",
      //表单数据对象
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        //商品所属分类数组
        goods_cat: [],
        //上传图片的数组
        pics: [],
        //商品介绍
        goods_introduce: "",
        attrs: [],
      },
      //表单验证规则
      rulesAdd: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
      },
      //动态参数列表数据
      manyData: [],
      //静态属性列表数据
      onlyData: [],
      //基本信息级联选择商品分类
      cateList: [],
      //级联选择配置
      configCascader: {
        label: "cat_name",
        value: "cat_id",
        children: "children",
        expandTrigger: "hover",
      },
      //放大图片弹窗
      dialogVisible: false,
      //放大图片的url
      dialogImageUrl: "",
      disabled: false,
      //文件上传列表   控制图片显示
      thislist: [],
      //图片上传请求头
      headers: {
        Authorization: window.sessionStorage.getItem("token"),
      },
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    //获取级联选择框的商品分类列表
    async getCateList() {
      const { data: res } = await this.axios.get("categories");
      if (res.meta.status !== 200) {
        return layer.msg(res.meta.msg, { time: 1000 });
      }
      this.cateList = res.data;
    },
    //级联选择选中触发
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },
    //切换tab钩子函数
    leaveTab(newIndex, oldIndex) {
      if (newIndex != "0") {
        if (this.addForm.goods_cat.length != 3) {
          layer.msg("此选项需要选择基本信息中的商品分类！", { time: 1000 });
          return false;
        }
      }
    },
    //tab发生改变函数
    async clickTab() {
      //商品参数
      if (this.activeIndex == "1") {
        const { data: res } = await this.axios.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" },
          }
        );
        if (res.meta.status !== 200) {
          return layer.msg(res.meta.msg, { time: 1000 });
        }
        res.data.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length == 0 ? [] : item.attr_vals.split(" ");
        });
        this.manyData = res.data;
      }
      //商品属性
      if (this.activeIndex == "2") {
        const { data: res } = await this.axios.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" },
          }
        );
        if (res.meta.status !== 200) {
          return layer.msg(res.meta.msg, { time: 1000 });
        }
        this.onlyData = res.data;
      }
      //商品图片
      if (this.activeIndex == "3") {
      }
      //商品内容
      if (this.activeIndex == "4") {
      }
    },
    //图片放大
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //删除图片
    handleRemove(file) {
      //从表单中删除需要删除的图片信息
      this.addForm.pics = this.addForm.pics.filter((item) => {
        item.pic !== file.response.data.tmp_path;
      });
      this.thislist = this.thislist.filter((item) => {
        item.uid !== file.uid;
      });
    },
    //上传成功的钩子
    success(res, file, fileList) {
      //上传成功 将数据保存到表单里
      this.addForm.pics.push({
        pic: res.data.tmp_path,
      });
      this.thislist = fileList;
    },
    //添加商品按钮
    addGoods() {
      this.$refs.addFormRef.validate(async (value) => {
        if (!value) {
          return layer.msg("请正确填写内容后再试！");
        }
        //深拷贝一个表单对象用来提交数据（避免数据绑定导致报错）
        const submitForm = _.cloneDeep(this.addForm);
        submitForm.goods_cat = submitForm.goods_cat.join(",");
        //处理attr属性
        //1动态参数
        this.manyData.forEach((item) => {
          const obj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(","),
          };
          this.addForm.attrs.push(obj);
        });
        //2静态属性
        this.onlyData.forEach((item) => {
          const obj = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals,
          };
          this.addForm.attrs.push(obj);
        });
        submitForm.attrs = this.addForm.attrs;
        //判断商品是否唯一
        const { data: res } = await this.axios.post("goods", submitForm);
        if (res.meta.status !== 201) {
          return layer.msg(res.meta.msg, { time: 1000 });
        }
        layer.msg(res.meta.msg, { time: 1000 }, () => {
          this.$router.push("/goods");
        });
      });
    },
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length == 3) {
        return this.addForm.goods_cat[2];
      } else {
        return null;
      }
    },
  },
};
</script>

<style scoped>
.el-steps {
  margin: 20px 0;
}
/deep/ .el-step__title {
  font-size: 12px !important;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.addBtn {
  margin: 10px auto;
}
</style>
